package com.qrxl.util;

import lombok.extern.slf4j.Slf4j;

/**
 * 字节转换
 *
 * @author wyd
 */
@Slf4j
public class HexStringUtils {

    /**
     * 将字符串转化为十六进制编码
     *
     * @param s
     * @return
     */
    public static String stringToHex(String s) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            str.append(Integer.toHexString((int) s.charAt(i)));
        }
        return str.toString();
    }

    /**
     * 将十六进制编码转化为字符串
     *
     * @param s
     * @return
     */
    public static String hexToString(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                log.error("", e);
            }
        }
        try {
            s = new String(baKeyword, "utf-8");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    /**
     * 将十六进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换为16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        //生产dbkey16byte
        String str = stringToHex("6l!o@o#k$d%o^o&r");
        //测试dbkey
        String str2 = stringToHex("lansent123456789");
        //生产dbkey16byte
        String str3 = stringToHex("l@o#o$k*");
        System.out.println(str);
        System.out.println(hexToString(str));
        System.out.println(str2);
        System.out.println(hexToString(str2));
        System.out.println(str3);
        System.out.println(hexToString(str3));
    }
}
